package com.boarsoft.boar.deploy.app.gateway;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;

import com.boarsoft.agent.AgentService;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.app.AppBiz;
import com.boarsoft.boar.config.service.ConfigFileService;
import com.boarsoft.boar.deploy.plan.bean.BuildRequest;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.boar.entity.ObjLabel;
import com.boarsoft.boar.label.ObjLabelBiz;
import com.boarsoft.common.util.InetUtil;
import com.boarsoft.flow.core.bean.ProcessHandler;

/**
 * 修改网关应用的gateway.properties中的路由配置
 * 
 * @author Mac_J
 *
 */
public class UpdRouteCfgPH implements ProcessHandler {
	private static final Logger log = LoggerFactory.getLogger(UpdRouteCfgPH.class);

	@Autowired
	@Lazy(value = true)
	@Qualifier("agentX")
	protected AgentService agentX;
	@Autowired
	protected ConfigFileService configFileSvc;
	@Autowired
	protected AppBiz appBiz;
	@Autowired
	protected ObjLabelBiz objLabelBiz;

	// gateway.properites";
	protected String fileId = "40284e817240fb1b01724180c224000c";

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildRequest br = (BuildRequest) data;
		AppInst inst1 = (AppInst) br.get("inst1"); // old target
		AppInst inst2 = (AppInst) br.get("inst2"); // new target
		String id1 = inst1.getId();
		// 根据应用的分组找到对应的网关的分组（可能返回多个），以确定文件版本的分组
		List<ObjLabel> lbLt = objLabelBiz.list(//
				id1, ObjLabel.TYPE_APP_INST, "gateway.group", null);
		if (lbLt.isEmpty()) {
			throw new IllegalStateException(String.format(//
					"Label gateway.group of app inst %s is missing", id1));
		}
		// 查找实例在网关路由表中的key
		ObjLabel ko = objLabelBiz.find(//
				id1, "gateway.key", ObjLabel.TYPE_APP_INST);
		if (lbLt.isEmpty()) {
			throw new IllegalStateException(String.format(//
					"Label gateway.key of app inst %s is missing", id1));
		}
		String pk = ko.getValue();
		// 修改所有受影响的网关分组
		for (ObjLabel lb : lbLt) {
			log.info("Modify {} of config file {}", pk, fileId);
			// 更新当前分组中配置文件对应的key（配置中心会自动同步）
			ReplyInfo<Object> ro = configFileSvc.replacePropVar(InetUtil.getIp(), //
					fileId, inst1.getEnv(), lb.getValue(), pk, inst1.getAddr(), inst2.getAddr());
			if (ro.isSuccess()) {
				continue;
			}
			// TODO 对不成功的处理（产生告警，转人工处理？）
			log.error("Modify config file {} failed, {}", fileId, ro.getData());
		}
		return data;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}
}